package com.atguigu.guli.service.ucenter.controller.api;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.ucenter.service.WxLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class ApiWxController {

    @Autowired
    WxLoginService wxLoginService;

    // 用户点击微信获取微信登录二维码
    @GetMapping("login")
    public String wxLogin(HttpSession session){

        String redirectUrl = wxLoginService.login(session);
        return redirectUrl;
    }

    //http://localhost:8160/api/ucenter/wx/callback?code=0816H8000lqe2M1Rx4100xvyRi46H80j&state=4c2ee8cd
    //2、用户授权后的回调   code代表wx用户的授权   state代表生成wx登录二维码的唯一token 防止恶意攻击
    @GetMapping("callback")//http://localhost:8160/api/ucenter/wx/callback
    public String callback(@RequestParam String code ,
                           @RequestParam String state,
                           HttpSession session){
        String redirectUrl = wxLoginService.callback(code,state,session);
        return redirectUrl;
    }

    /*public String wxLogin(HttpSession session) {

        try {
            String url = "https://open.weixin.qq.com/connect/qrconnect" +
                    "?appid=%s" +  //应用在wx平台注册的应用id
                    "&redirect_uri=%s" +  //用户授权后的回调地址  需要进行UrlEncode
                    "&response_type=code" +
                    "&scope=snsapi_login" +
                    "&state=%s" +  // 随机数字
                    "#wechat_redirect";

            // wx登录 在微信平台注册的应用需要设置一个 域名，如果我们设置的redirectUri域名和 配置的不一致，则报错
            String redirectUri = "http://localhost:8160/api/ucenter/wx/callback8160";
            String state = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            session.setAttribute("wxStater", state);

            url = String.format(url,  //将带占位符的字符串的参数设置好 并接收返回的字符串
                    "wxed9954c01bb89b47", URLEncoder.encode(redirectUri, "UTF-8"), state
            );

            //重定向
            return "redirect:" + url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
    }*/



}
